<?php

declare(strict_types=1);

namespace App\Service;

use App\Model\DistributionCenter;
use App\Model\FlyBusinessDistrict;
use App\Model\FlyBusinessDistrictLinkShop;
use App\Model\FlyGourmetMealConf;
use App\Model\FlyShop;
use App\Model\FlyShopCertificate;
use App\Model\FlyShopCertificateAtt;
use App\Model\FlyShopSet;
use App\Model\FlyShopVipsOrder;
use Hyperf\Di\Annotation\Inject;
use \App\Service\FlyShopUserVipService;
use App\Model\FlyShopUserVip;
use Hyperf\Database\Model\Relations\HasMany;
use Hyperf\Database\Query\Builder;
use Hyperf\Database\Model\Builder as ModelBuilder;
use Hyperf\DbConnection\Db;

class FlyBusinessDistrictService extends BaseService
{
    /**
     * @Inject
     * @var LinkFileService
     */
    private $LinkFileService;

    /**
     * @Inject
     * @var FlyShopService
     */
    private $FlyShopService;

    /**
     * @Inject
     * @var FlyGourmetMealConfService
     */
    private $FlyGourmetMealConf;

    /**
     * @Inject
     * @var ReservedSeatsService
     */
    private $ReservedSeatsService;



    /**
     * Notes:
     * @param array $request_p
     * @return ModelBuilder|mixed
     * Date: 2022/7/28
     * Time:14:42
     * Auth: zdl
     */
    public function list(array $request_p=[])
    {
        $key_word = $request_p['key_word'];
        $lat = floatval($request_p['lat']);
        $lng = floatval($request_p['lng']);
       return FlyBusinessDistrict::query()
           ->where('is_show','1')
           ->with('pic_list')
           ->when($key_word,function ($query) use($key_word){
               $query->where('name','like','%'.$key_word.'%');
            })

           ->select(['*', Db::raw(" TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) as distance_meter")])
           ->orderBy('distance_meter');
    }

    /**
     * Notes:
     * @param int $district_id
     * @param $lng
     * @param $lat
     * @return ModelBuilder|mixed
     * Date: 2022/7/28
     * Time:14:42
     * Auth: zdl
     */
    public function info(int $district_id,float $lng=0,float $lat=0)
    {
        if($lng&&$lat){
            return FlyBusinessDistrict::query()
                ->where('is_show','1')
                ->where('id',$district_id)
                ->with('pic_list')
                ->first(['*', Db::raw(" TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) as distance_meter")]);
        }else{
            return FlyBusinessDistrict::query()
                ->where('is_show','1')
                ->with('pic_list')
                ->first();
        }
    }

    /**
     * Notes:
     * @param array $request_p
     * @return ModelBuilder|mixed
     * Date: 2022/7/28
     * Time:14:42
     * Auth: zdl
     */
    public function shop_list(array  $request_p)
    {
        $key_word = $request_p['key_word'];
        $where = [];$district_where = [];

        $is_service = false;$shop_ids = [];
        if(isset($request_p['district_id'])&&$request_p['district_id']!=''){
            $district_where['fly_business_district_link_shop.district_id'] = $request_p['district_id'];
        }
        $district_where['fly_business_district.is_show'] = 1;
        $shop_ids =  FlyBusinessDistrictLinkShop::query()
            ->leftJoin('fly_business_district','fly_business_district.id','=','fly_business_district_link_shop.district_id')
            ->where($district_where)
            ->groupBy('fly_business_district_link_shop.shop_id')
            ->pluck('fly_business_district_link_shop.shop_id')
            ->toArray();
        if(isset($request_p['distance_meter'])&&$request_p['distance_meter']!=''){
            $distance_meter = $request_p['distance_meter'];
        }else{
            $distance_meter  = 100;
        }
        if(isset($request_p['service'])&&$request_p['service']!=[]){
            $is_service = true;
            $shop_ids_a = $shop_ids_b = [];
           if(in_array(1,$request_p['service'])){
               $shop_ids_a = $this->FlyGourmetMealConf->get_meal_shop();
           }
            if(in_array(2,$request_p['service'])){
                $shop_ids_b = $this->ReservedSeatsService->get_reserved_shop();
            }
            $shop_ids = array_intersect($shop_ids,array_unique(array_merge($shop_ids_a,$shop_ids_b)));
        }
        $is_open_time = false;$shop_ids_c = [];
        if(isset($request_p['start_time'])&&isset($request_p['end_time'])&&$request_p['start_time']!=''&&$request_p['end_time']!=''){
            $is_open_time = true;
            $shop_ids_c = $this->FlyShopService->open_shop($request_p['start_time'],$request_p['end_time']);
            $shop_ids = array_intersect($shop_ids,$shop_ids_c);
        }
        $column = 'distance_meter'; $order_by = 'ASC';
        if(isset($request_p['order_by'])&&$request_p['order_by']!=''){
            if($request_p['order_by']==2){
                $column = 'food_avg_score';$order_by = 'DESC';
            }
            if($request_p['order_by']==3){
                $column = 'food_sales_volume';$order_by = 'DESC';
            }
        }
        $lat = floatval($request_p['lat']);
        $lng = floatval($request_p['lng']);
        $FlyShopModel  = New FlyShop();
        $un_shop_ids = $FlyShopModel
            ->where('food_state',0)
            ->Where('shop_state',0)
            ->pluck('id')
            ->toArray();
        return $FlyShopModel
            ->leftJoin('fly_business_district_link_shop as ls','fly_shop.id','=','ls.shop_id')
            ->where($where)
            ->with('food_list')
            ->whereIn('fly_shop.id',$shop_ids)
            ->whereNotIn('fly_shop.id',$un_shop_ids)
            ->whereRaw("TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) < $distance_meter")
            ->when($key_word,function ($query) use($key_word){
                $query->where('fly_shop.shop_name','like','%'.$key_word.'%');
            })
            ->select(['fly_shop.*',
                'ls.created_at as join_district_time',
                'ls.id as link_id',
                'ls.district_id',
                Db::raw("TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) as distance_meter")])
            ->orderBy($column,$order_by)
            ->with(['with_industry','center_info','apply_info','certificate_att','reserved_set','meal_set']);
//        return FlyBusinessDistrictLinkShop::query()
//            ->leftJoin('fly_shop','fly_shop.id','=','fly_business_district_link_shop.shop_id')
//            ->where($where)
//            ->whereRaw("TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) < $distance_meter")
//            ->when($key_word,function ($query) use($key_word){
//                $query->where('fly_business_district_link_shop.name','like','%'.$key_word.'%');
//            })
//            ->when($is_service,function ($query) use($shop_ids){
//                $query->whereIn('fly_shop.id',$shop_ids);
//            })
//            ->when($is_open_time,function ($query) use($shop_ids_c){
//                $query->whereIn('fly_shop.id',$shop_ids_c);
//            })
//            ->select(['fly_shop.*', Db::raw("TRUNCATE(st_distance_sphere(point($lng,$lat),point(lng,lat))/1000,2) as distance_meter")])
//            ->orderBy($column,$order_by)
//            ->with(['with_industry','center_info','apply_info','certificate_att','reserved_set','meal_set']);
    }

    /**
     * Notes:
     * @param array $param
     * Date: 2022/7/28
     * Time:13:44
     * Auth: zdl
     * @return int
     */
    public function add($param)
    {
        $banner = [];
        if(isset($param['banner'])){
            $banner = $param['banner'];unset($param['banner']);
        }
        $id =  FlyBusinessDistrict::query()->insertGetId($param);
        if(count($banner)>0){
            $this->LinkFileService->link_file_insert($banner,$id,7);
        }
        return $id;
    }
    public function edit($param)
    {
        $banner = [];
        if(isset($param['banner'])){
            $banner = $param['banner'];unset($param['banner']);
        }
        $res = FlyBusinessDistrict::query()->where('id',$param['id'])->update($param);
        if(count($banner)>0){
            $this->LinkFileService->link_file_insert($banner,$param['id'],7);
        }
        return $res;
    }

    public function del_shop(int $district_id,int $shop_id)
    {
        return FlyBusinessDistrictLinkShop::query()
            ->where('district_id',$district_id)
            ->where('shop_id',$shop_id)
            ->delete();
    }

    public function add_shop(int $district_id,int $shop_id)
    {
        return FlyBusinessDistrictLinkShop::query()->insertGetId([
            'district_id'=>$district_id,
            'shop_id'=>$shop_id,
        ]);
    }


}